package com.hjm.project.accounts.virtualPolicy.service.impl;

import java.io.File;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.ExceptionUtil;
import com.hjm.common.utils.excel.OutExcel;
import com.hjm.common.utils.file.FileUtils;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.yh.PoiUtil;
import com.hjm.project.accounts.virtualPolicyRecord.domain.VirtualPolicyRecord;
import com.hjm.project.accounts.virtualPolicyRecord.mapper.VirtualPolicyRecordMapper;
import com.hjm.project.job.task.domain.JobTask;
import com.hjm.project.merchantInfo.merchantInfo.domain.MerchantInfo;
import com.hjm.project.merchantInfo.merchantInfo.mapper.MerchantInfoMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.hjm.project.accounts.virtualPolicy.mapper.VirtualPolicyMapper;
import com.hjm.project.accounts.virtualPolicy.domain.VirtualPolicy;
import com.hjm.project.accounts.virtualPolicy.service.IVirtualPolicyService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商户虚户政策Service业务层处理
 * 
 * @author maker-platform
 * @date 2022-03-14
 */
@Service
public class VirtualPolicyServiceImpl implements IVirtualPolicyService {
    protected AtomicBoolean valiFalg = new AtomicBoolean(true);
    @Resource
    private VirtualPolicyMapper virtualPolicyMapper;

    @Resource
    private VirtualPolicyRecordMapper policyRecordMapper;

    @Resource
    private MerchantInfoMapper merchantInfoMapper;


    /**
     * 查询商户虚户政策
     * 
     * @param id 商户虚户政策ID
     * @return 商户虚户政策
     */
    @Override
    public VirtualPolicy selectVirtualPolicyById(Integer id) {
        return virtualPolicyMapper.selectVirtualPolicyById(id);
    }

    /**
     * 查询商户虚户政策列表
     * 
     * @param virtualPolicy 商户虚户政策
     * @return 商户虚户政策
     */
    @Override
    public List<VirtualPolicy> selectVirtualPolicyList(VirtualPolicy virtualPolicy) {
        return virtualPolicyMapper.selectVirtualPolicyList(virtualPolicy);
    }

    /**
     * 新增商户虚户政策
     *
     * @param virtualPolicy 商户虚户政策
     * @return 结果
     */
    @Override
    @Async("threadPoolTaskExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public CompletableFuture<JobTask> insertVirtualPolicy(VirtualPolicy virtualPolicy, File files) {
        String downloadFileName = FileUtils.getDownloadFileName();
        JobTask jobTask = new JobTask();
        jobTask.setOperatorType(Long.parseLong("7"));
        jobTask.setOperatorContent("导入成功");
        jobTask.setCreateBy(ShiroUtils.getLoginName());
        jobTask.setFileName(FileUtils.getDownloadLastPath() + downloadFileName);
        try{
            Map<String, Map<String, Object>> lines = PoiUtil.readExcelContent(files.getPath());
            //如果excel没有数据，就不进行处理
            if (lines.size() <= 0) {
                jobTask.setOperatorContent("空文件不可导入");

                this.valiFalg = new AtomicBoolean(false);
            } else if (lines.size() > 10000) {
                jobTask.setOperatorContent("商户数量超过一万");
                this.valiFalg = new AtomicBoolean(false);
            }
            if (!this.valiFalg.get()) {
                return CompletableFuture.completedFuture(jobTask);
            }
            List<String[]> list = new ArrayList<>();
            //成功结果数量
            AtomicInteger success = new AtomicInteger(0);
            //失败结果数量
            AtomicInteger error = new AtomicInteger(0);
            for (int i = 1; i < lines.size()+1; i++) {
                //读取到的数据
                Map<String, Object> data = lines.get("key" + i);
                String merNo = String.valueOf(data.get("key0"));
                //需写入的结果信息
                String[] exportData = new String[2];
                exportData[0] = merNo;
                exportData[1] = "导入成功";

                //查看商户是否存在
                MerchantInfo merchantInfo = merchantInfoMapper.selectMerchantInfoById(merNo);
                if (merchantInfo == null) {
                    exportData[1] = "导入失败,不存在的商户";
                    list.add(exportData);
                    error.getAndIncrement();
                    continue;
                }


                //查看商户是否已导入
                VirtualPolicy policy = new VirtualPolicy();
                policy.setMerNo(merNo);
                List<VirtualPolicy> virtualPolicies = virtualPolicyMapper.selectVirtualPolicyList(policy);
                if (virtualPolicies.size() > 0) {
                    exportData[1] = "导入失败,当前商户已经导入";
                    list.add(exportData);
                    error.getAndIncrement();
                    continue;
                }

                //添加商户规则信息
                VirtualPolicy insertPolicy = new VirtualPolicy();
                insertPolicy.setMerNo(merNo);
                insertPolicy.setMaxTx(virtualPolicy.getMaxTx());
                insertPolicy.setCycleTx(virtualPolicy.getCycleTx());
                insertPolicy.setCycleDate(virtualPolicy.getCycleDate());
                insertPolicy.setTypes(virtualPolicy.getTypes());
                insertPolicy.setSource(2);
                insertPolicy.setAddMan(ShiroUtils.getLoginName());
                insertPolicy.setStatus(1);
                insertPolicy.setCreateDateTime(new Date());
                insertPolicy.setUpdateDateTime(new Date());
                insertPolicy.setFileName(virtualPolicy.getFileName());
                int k = virtualPolicyMapper.insertVirtualPolicy(insertPolicy);
                if (k == 0) {
                    exportData[1] = "导入新增失败";
                    list.add(exportData);
                    error.getAndIncrement();
                    continue;
                }
                list.add(exportData);
                success.getAndIncrement();
            }

            String[] title = {"商户编号","导入结果"};
            OutExcel.outExcel(FileUtils.getDownloadPathName(),downloadFileName,"导入商户提现规则",title,list);
            jobTask.setOperatorContent("导入结果:" + success.get() + "条成功," + error.get() + "条失败");
        }catch (Exception e){
            jobTask.setOperatorContent("导入异常:" + ExceptionUtil.getExceptionMessage(e).substring(0,150));
            e.printStackTrace();
        }
        return CompletableFuture.completedFuture(jobTask);
    }

    /**
     * 查询商户虚户政策列表
     *
     * @param virtualPolicy 商户虚户政策
     * @return 商户虚户政策 一个结果
     */
    @Override
    public VirtualPolicy selectVirtualPolicyOne(VirtualPolicy virtualPolicy) {
        return virtualPolicyMapper.selectVirtualPolicyOne(virtualPolicy);
    }

    /**
     * 修改商户虚户政策
     * 
     * @param virtualPolicy 商户虚户政策
     * @return 结果
     */
    @Override
    public int updateVirtualPolicy(VirtualPolicy virtualPolicy) {
        VirtualPolicy oldVir = virtualPolicyMapper.selectVirtualPolicyById(virtualPolicy.getId());
        int i = virtualPolicyMapper.updateVirtualPolicy(virtualPolicy);
        if (i == 0) {
            throw new BusinessException("更新失败");
        }
        //添加记录
        VirtualPolicyRecord virtualPolicyRecord = new VirtualPolicyRecord();
        virtualPolicyRecord.setAddMan(ShiroUtils.getLoginName());
        virtualPolicyRecord.setMerNo(oldVir.getMerNo());
        virtualPolicyRecord.setSource(2);
        virtualPolicyRecord.setBeforeType(oldVir.getTypes());
        virtualPolicyRecord.setAfterType(virtualPolicy.getTypes());
        virtualPolicyRecord.setBeforeMaxTx(oldVir.getMaxTx().toString());
        virtualPolicyRecord.setAfterMaxTx(virtualPolicy.getMaxTx().toString());
        virtualPolicyRecord.setBeforeCycleTx(oldVir.getCycleTx().toString());
        virtualPolicyRecord.setAfterCycleTx(virtualPolicy.getCycleTx().toString());
        virtualPolicyRecord.setBeforeCycleDate(oldVir.getCycleDate());
        virtualPolicyRecord.setAfterCycleDate(virtualPolicy.getCycleDate());
        virtualPolicyRecord.setCreateDateTime(DateUtils.getDateTime());
        return policyRecordMapper.insertVirtualPolicyRecord(virtualPolicyRecord);
    }

    /**
     * 删除商户虚户政策对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteVirtualPolicyByIds(String ids) {
        return virtualPolicyMapper.deleteVirtualPolicyByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商户虚户政策信息
     * 
     * @param id 商户虚户政策ID
     * @return 结果
     */
    @Override
    public int deleteVirtualPolicyById(Integer id) {
        return virtualPolicyMapper.deleteVirtualPolicyById(id);
    }
}
